﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Collections;

namespace OMap {
	/// <summary>
	/// This class implements the property matching logic.
	/// </summary>
    public sealed class PropertyMatch {
        public PropertyInfo SourceProperty { get; set; }
        public PropertyInfo DestinationProperty{ get; set;}

        public IObjectMapper ObjectMapper{ get; set;}

        public PropertyMatch(PropertyInfo sourceProp, PropertyInfo destinationProp) {
            SourceProperty = sourceProp;
            DestinationProperty = destinationProp;
        }


        public static IEnumerable<PropertyMatch> CreateMatches(Type sourceType, Type targetType,OMap oMap,bool overwriteIfNotDefault) {
            var sourceProps = sourceType.GetProperties();
            var destinationProps = targetType.GetProperties();
            var matches = new List<PropertyMatch>();


            foreach (var sourceProp in sourceProps) {
                foreach (var destinationProp in destinationProps) {
                    if ((sourceProp.Name.Equals(destinationProp.Name, StringComparison.InvariantCultureIgnoreCase))) {

                        PropertyMatch match = new PropertyMatch(sourceProp, destinationProp);

                        if (!destinationProp.PropertyType.IsAssignableFrom(sourceProp.PropertyType)) {
                            match.ObjectMapper = oMap.GetMapper(sourceProp.PropertyType, destinationProp.PropertyType,overwriteIfNotDefault,true);
                        }
                        matches.Add(match);
                    }
                }

            }
            return matches;
        }
    }
}
